import platform
from threading import Lock

from subprocess import Popen, PIPE
from src.process.base_pro_handler import BaseProHandler


class SubProHandler(BaseProHandler):

    def __init__(self, argv):
        self.__write_lock = Lock()
        # Linux, macOS下shell应为true
        # Windows设为true将无法强制关闭
        shell_option = False
        if platform.system() != "Windows":
            shell_option = True
        self.__proc = Popen(argv, stdout=PIPE, stdin=PIPE, shell=shell_option)

    def write(self, command: str):
        command = command + "\r\n"
        byte_command: bytes = command.encode()
        with self.__write_lock:
            self.__proc.stdin.write(byte_command)
            self.__proc.stdin.flush()

    def readline(self) -> str:
        next_bytes: bytes = self.__proc.stdout.readline()
        try:
            next_line = next_bytes.decode("utf-8")
        except UnicodeDecodeError:
            try:
                next_line = next_bytes.decode("gbk")
            except Exception as e:
                next_line = str(e)
        return next_line

    def poll(self) -> int | None:
        return self.__proc.poll()

    def terminate(self):
        self.__proc.terminate()

    def kill(self):
        self.__proc.kill()

    def wait(self, wait_time: float = None) -> int | None:
        return self.__proc.wait(wait_time)
